/**
 * 结果展示页面
 */

import React, { useState } from 'react';
import { Row, Col, Typography, Steps, Alert, Tag } from 'antd';
import { CheckCircleOutlined, ExclamationCircleOutlined, WarningOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import { themeConfig } from '../theme/themeConfig';
import { Card } from '../components/ui/Card';
import { Button } from '../components/ui/Button';
import LanguageList from '../components/result/LanguageList';
import { useLanguageState } from '../store/appStore';
import { FileService } from '../services/fileService';
import { downloadAllFilesAsZip } from '../utils/fileUtils';
import { generateDartFileContentForDocs } from '../utils/languageUtils';

const { Title, Paragraph } = Typography;
const { Step } = Steps;

const PageContainer = styled.div`
  min-height: 100vh;
  background-color: ${themeConfig.colors.background};
  padding: ${themeConfig.spacing.xl};
`;

const ContentContainer = styled.div`
  max-width: 1200px;
  margin: 0 auto;
`;

const HeaderSection = styled.div`
  text-align: center;
  margin-bottom: ${themeConfig.spacing.xxl};
`;

const MainTitle = styled(Title)`
  color: ${themeConfig.colors.text} !important;
  margin-bottom: ${themeConfig.spacing.md} !important;
`;

const SubTitle = styled(Paragraph)`
  color: ${themeConfig.colors.textSecondary} !important;
  font-size: ${themeConfig.typography.fontSize.body} !important;
  margin-bottom: 0 !important;
`;

const StepsContainer = styled.div`
  margin-bottom: ${themeConfig.spacing.xxl};
  
  .ant-steps-item-process .ant-steps-item-icon {
    background-color: ${themeConfig.colors.primary};
    border-color: ${themeConfig.colors.primary};
  }
  
  .ant-steps-item-finish .ant-steps-item-icon {
    background-color: ${themeConfig.colors.primary};
    border-color: ${themeConfig.colors.primary};
  }
`;

const ActionSection = styled.div`
  display: flex;
  justify-content: center;
  gap: ${themeConfig.spacing.md};
  margin-top: ${themeConfig.spacing.xl};
`;

const ConflictListContainer = styled.div`
  .conflict-item {
    padding: ${themeConfig.spacing.md};
    border-left: 4px solid ${themeConfig.colors.warning};
    background-color: #FFF7E6;
    border-radius: ${themeConfig.borderRadius.small};
    margin-bottom: ${themeConfig.spacing.sm};
  }
  
  .conflict-type {
    font-weight: ${themeConfig.typography.fontWeight.medium};
    color: ${themeConfig.colors.text};
    margin-bottom: ${themeConfig.spacing.xs};
  }
  
  .conflict-message {
    color: ${themeConfig.colors.textSecondary};
    font-size: ${themeConfig.typography.fontSize.body};
  }
`;

interface ResultPageProps {
  onReset: () => void;
}

export const ResultPage: React.FC<ResultPageProps> = ({ onReset }) => {
  const { languageFiles, detectionReport } = useLanguageState();
  const [selectedLanguages, setSelectedLanguages] = useState<string[]>([]);
  const [selectAll, setSelectAll] = useState(false);

  const handleDownloadAll = async () => {
    try {
      await downloadAllFilesAsZip(languageFiles, generateDartFileContentForDocs);
    } catch (error) {
      console.error('下载失败:', error);
    }
  };

  const handleDownloadSelected = async () => {
    try {
      const selectedFiles = languageFiles.filter(file => selectedLanguages.includes(file.code));
      if (selectedFiles.length === 0) {
        return;
      }
      await downloadAllFilesAsZip(selectedFiles, generateDartFileContentForDocs);
    } catch (error) {
      console.error('下载失败:', error);
    }
  };

  const handleSelectLanguage = (languageCode: string, checked: boolean) => {
    if (checked) {
      setSelectedLanguages(prev => [...prev, languageCode]);
    } else {
      setSelectedLanguages(prev => prev.filter(code => code !== languageCode));
    }
  };

  const handleSelectAll = (checked: boolean) => {
    setSelectAll(checked);
    if (checked) {
      setSelectedLanguages(languageFiles.map(file => file.code));
    } else {
      setSelectedLanguages([]);
    }
  };

  const handleDownloadSingle = (file: any) => {
    try {
      const content = generateDartFileContentForDocs(file);
      FileService.downloadSingleFile(file.fileName, content);
    } catch (error) {
      console.error('下载失败:', error);
    }
  };

  const getConflictIcon = (type: string) => {
    switch (type) {
      case 'duplicate':
        return <ExclamationCircleOutlined style={{ color: themeConfig.colors.error }} />;
      case 'missing':
        return <WarningOutlined style={{ color: themeConfig.colors.warning }} />;
      case 'format_error':
        return <ExclamationCircleOutlined style={{ color: themeConfig.colors.info }} />;
      default:
        return <ExclamationCircleOutlined style={{ color: themeConfig.colors.textSecondary }} />;
    }
  };

  const getConflictSeverity = (severity: string) => {
    switch (severity) {
      case 'high':
        return <Tag color="red">高</Tag>;
      case 'medium':
        return <Tag color="orange">中</Tag>;
      case 'low':
        return <Tag color="blue">低</Tag>;
      default:
        return <Tag color="default">未知</Tag>;
    }
  };

  return (
    <PageContainer>
      <ContentContainer>
        <HeaderSection>
          <MainTitle level={1}>
            处理完成
          </MainTitle>
          <SubTitle>
            文件处理完成，以下是生成的结果和检测报告
          </SubTitle>
        </HeaderSection>

        <StepsContainer>
          <Steps current={2} size="small">
            <Step title="上传文件" description="文件已上传" />
            <Step title="处理文件" description="处理已完成" />
            <Step title="下载结果" description="查看生成的文件" />
          </Steps>
        </StepsContainer>

        <Row gutter={[24, 24]}>
          <Col xs={24} lg={16}>
            <LanguageList
              files={languageFiles}
              onDownloadFile={handleDownloadSingle}
              onDownloadAll={handleDownloadAll}
              onDownloadSelected={handleDownloadSelected}
              onSelectLanguage={handleSelectLanguage}
              onSelectAll={handleSelectAll}
              selectedLanguages={selectedLanguages}
              selectAll={selectAll}
              conflicts={detectionReport?.conflicts || []}
              missingTranslations={detectionReport?.conflicts.filter(c => c.type === 'missing') || []}
            />
          </Col>
          
          <Col xs={24} lg={8}>
            <Card title="检测报告" variant="outlined">
              {detectionReport && detectionReport.conflicts.length > 0 ? (
                <div>
                  <Alert
                    message="发现翻译问题"
                    description={`共发现 ${detectionReport.conflicts.length} 个问题，建议检查并修复`}
                    type="warning"
                    showIcon
                    style={{ marginBottom: themeConfig.spacing.md }}
                  />
                  
                  <ConflictListContainer>
                    {detectionReport.conflicts.map((conflict, index) => (
                      <div key={index} className="conflict-item">
                        <div className="conflict-type">
                          {getConflictIcon(conflict.type)}
                          {getConflictSeverity(conflict.severity)}
                          {conflict.key}
                        </div>
                        <div className="conflict-message">
                          {conflict.message}
                        </div>
                      </div>
                    ))}
                  </ConflictListContainer>
                </div>
              ) : (
                <div style={{ textAlign: 'center', padding: themeConfig.spacing.lg }}>
                  <CheckCircleOutlined style={{ fontSize: 48, color: themeConfig.colors.success, marginBottom: themeConfig.spacing.md }} />
                  <div style={{ color: themeConfig.colors.success, fontWeight: themeConfig.typography.fontWeight.medium }}>
                    未发现翻译问题
                  </div>
                  <div style={{ color: themeConfig.colors.textSecondary, fontSize: themeConfig.typography.fontSize.caption, marginTop: themeConfig.spacing.sm }}>
                    所有翻译数据完整且格式正确
                  </div>
                </div>
              )}
            </Card>
          </Col>
        </Row>

        <ActionSection>
          <Button
            variant="outline"
            onClick={onReset}
          >
            重新开始
          </Button>
        </ActionSection>
      </ContentContainer>
    </PageContainer>
  );
};
